package com.ruicar.afs.cloud.gateway.util;

import cn.hutool.core.util.StrUtil;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.util.ClientTypeUtil;
import lombok.experimental.UtilityClass;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.reactive.function.server.ServerRequest;
import java.util.List;

@UtilityClass
public class AfsGateWayHelper {
    public String getHeaderValue(ServerWebExchange exchange,String headerName){
        String headerValue = exchange.getRequest().getHeaders().getFirst(headerName);
        if (StrUtil.isEmpty(headerValue)) {
            headerValue = exchange.getRequest().getQueryParams().getFirst(headerName);
        }
        if (StrUtil.isEmpty(headerValue)) {
            if(exchange.getRequest().getCookies().getFirst(headerName)!=null) {
                headerValue = exchange.getRequest().getCookies().getFirst(headerName).getValue();
            }
        }
        return headerValue;
    }

    public  ClientTypeUtil.ClientTypeEnum getClientType(ServerRequest request) {
        List<String> userAgents = request.headers().header("User-Agent");
        if (userAgents == null || userAgents.size() == 0) {
            throw new AfsBaseException(CommonConstants.FAIL, "not allowed");
        } else {
            return ClientTypeUtil.getClientType(userAgents.get(0));
        }
    }
}
